from fastapi import FastAPI, UploadFile, File
from fastapi.staticfiles import StaticFiles
import os
from app.database import init_db
from app.database import get_db
from app.routers import user_router  # 导入 user_router
#导入文章相关的路由
from app.routers import article_router

app = FastAPI()

# 注册 user_router
app.include_router(user_router.router)
# 注册 article_router
app.include_router(article_router.router)

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="app/static"), name="static")

@app.get("/")
async def hello():
    return {"message": "Hello World"}

@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello, {name}!"}

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    # 确保上传目录存在
    upload_dir = "app/static/upload"
    os.makedirs(upload_dir, exist_ok=True)

    # 保存文件
    file_path = os.path.join(upload_dir, file.filename)
    with open(file_path, "wb") as buffer:
        buffer.write(await file.read())

    # 返回文件的访问 URL
    file_url = f"/static/upload/{file.filename}"
    return {"message": "文件上传成功", "file_url": file_url}

if __name__ == "__main__":
    import uvicorn
    # 初始化数据库
    init_db()
    db = get_db()
    print(db)
    uvicorn.run(app, host="0.0.0.0", port=8000)